<html lang="en-US">

<head>
    
<title>Go 泛型玩出花，详解新提案 switch type！ - 花落雨忧</title>

<meta property="og:title" content="Go 泛型玩出花，详解新提案 switch type！ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
前面写过好几篇 Go 泛型的语法、案例介绍，新的一手 Go 消息。实际上，随着一些提案被接受，新的提案也逐渐冒出。
这不，我发现有了泛型后，大家可以更进一步玩出花来了。看到了一个 ”新“ 提案《proposal: spec: generics: type switch on parametric types》，讲的就是增加泛型后的参数类型上的类型开关诉求。 &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
前面写过好几篇 Go 泛型的语法、案例介绍，新的一手 Go 消息。实际上，随着一些提案被接受，新的提案也逐渐冒出。
这不，我发现有了泛型后，大家可以更进一步玩出花来了。看到了一个 ”新“ 提案《proposal: spec: generics: type switch on parametric types》，讲的就是增加泛型后的参数类型上的类型开关诉求。 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/switch-type/">Go 泛型玩出花，详解新提案 switch type！</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/12/31</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>前面写过好几篇 Go 泛型的语法、案例介绍，新的一手 Go 消息。实际上，随着一些提案被接受，新的提案也逐渐冒出。</p>
<p>这不，我发现有了泛型后，大家可以更进一步玩出花来了。看到了一个 ”新“ 提案《<a href="https://github.com/golang/go/issues/45380" title="proposal: spec: generics: type switch on parametric types">proposal: spec: generics: type switch on parametric types</a>》，讲的就是增加泛型后的参数类型上的类型开关诉求。</p>
<p>跟着煎鱼一起掌握新的 Go 知识吧！</p>
<h2 id="新提案">新提案</h2>
<p>新的提案内容是希望增加一个新的变种语句，允许在 switch 语句中使用泛型时，能够进一步便捷的约束其类型参数。</p>
<p>例如：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">switch</span> <span style="color:#66d9ef">type</span> <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#a6e22e">A1</span>:
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#a6e22e">A2</span>, <span style="color:#a6e22e">A3</span>:
</span></span><span style="display:flex;"><span>   <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>也就是 switch-type 语句的 <strong>T 类型可以是一个泛型的类型参</strong>，case 所对应的的类型可以是任何类型，包括泛型的约束类型。</p>
<p>假设类型 T 的类型有可能是以下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span>{
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">C</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">A</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>可以借助泛型的近似元素来约束：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>    <span style="color:#66d9ef">interface</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">C</span>
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">A1</span> | <span style="color:#a6e22e">A2</span> | <span style="color:#f92672">...</span> | <span style="color:#a6e22e">An</span>
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p>甚至还可以在 case 上有新的写法：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#66d9ef">interface</span> {~<span style="color:#a6e22e">T</span>}:
</span></span></code></pre></div><p>在支持泛型后，<strong>switch 在 type 和 case 上会存在很多种可能性</strong>，需要进行具体的特性支持，这个提案就是为此出现。</p>
<h2 id="实际案例">实际案例</h2>
<h3 id="案例一多类型元素">案例一：多类型元素</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Stringish</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">string</span> | <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Stringer</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Concat</span>[<span style="color:#a6e22e">S</span> <span style="color:#a6e22e">Stringish</span>](<span style="color:#a6e22e">x</span> []<span style="color:#a6e22e">S</span> <span style="color:#e6db74">&#34;S Stringish&#34;</span>) <span style="color:#66d9ef">string</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">switch</span> <span style="color:#66d9ef">type</span> <span style="color:#a6e22e">S</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">string</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Stringer</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span> }
</span></span></code></pre></div><p>类型 S 能够支持 string 和 fmt.Stringer 类型，case 配套对应实现。</p>
<h3 id="案例二近似元素">案例二：近似元素</h3>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Constraint</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>    ~<span style="color:#66d9ef">int</span> | ~<span style="color:#66d9ef">int8</span> | ~<span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">ThisSyntax</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">Constraint</span>]( <span style="color:#e6db74">&#34;T Constraint&#34;</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">switch</span> <span style="color:#66d9ef">type</span> <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> ~<span style="color:#66d9ef">int</span> | ~<span style="color:#66d9ef">int8</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> ~<span style="color:#66d9ef">string</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">IsClearerThanThisSyntax</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">Constraint</span>]( <span style="color:#e6db74">&#34;T Constraint&#34;</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">switch</span> <span style="color:#66d9ef">type</span> <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">interface</span>{~<span style="color:#66d9ef">int</span> | ~<span style="color:#66d9ef">int8</span> }:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">interface</span>{ ~<span style="color:#66d9ef">string</span> }:
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>类型 T 可能有很多类型，程序中用到了近似元素，也就是基础类型是 int、int8、string，这些类型中的任何一种都能够满足这个约束。</p>
<p>为此，switch-type 支持了，case 也要配套支持该特性。</p>
<h2 id="争议点">争议点</h2>
<p>看到这里可能大家也想到了，这个味道很似曾相识，好像某个语法能够支持。因此，这个提案下最有争议的，就是与原有的类型断言的重复。</p>
<p>原有的类型断言如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">switch</span> <span style="color:#a6e22e">T</span>.(<span style="color:#66d9ef">type</span>) {
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#66d9ef">string</span>:
</span></span><span style="display:flex;"><span>   <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">default</span>:
</span></span><span style="display:flex;"><span>   <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>新的类型判别如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">switch</span> <span style="color:#66d9ef">type</span> <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#a6e22e">A1</span>:
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">case</span> <span style="color:#a6e22e">A2</span>, <span style="color:#a6e22e">A3</span>:
</span></span><span style="display:flex;"><span>   <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>这么咋一看，其实类型断言的完全可以取代新的，那岂不是重复建设，造轮子了？</p>
<p>其实是没有完全取代的。差异点如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">ApproxString</span> <span style="color:#66d9ef">interface</span> { ~<span style="color:#66d9ef">string</span> }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">F</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">ApproxString</span>](<span style="color:#a6e22e">v</span> <span style="color:#a6e22e">T</span> <span style="color:#e6db74">&#34;T ApproxString&#34;</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">switch</span> (<span style="color:#66d9ef">interface</span>{})(<span style="color:#a6e22e">v</span>).(<span style="color:#66d9ef">type</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">string</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">default</span>:
</span></span><span style="display:flex;"><span>        panic(<span style="color:#e6db74">&#34;脑子没进煎鱼&#34;</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">MyString</span> <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">F</span>(<span style="color:#a6e22e">MyString</span>(<span style="color:#e6db74">&#34;脑子进煎鱼了&#34;</span>))
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>看出来差别在哪了吗，答案是什么？</p>
<p>答案是：会抛出恐慌（panic）。</p>
<p>你可能纠结了，问题出在哪里？这传入的 ”脑子进煎鱼了“ 的类型是 <code>MyString</code>，他的基础类型是 <code>string</code> 类型，也满足 <code>ApproxString</code> 类型的近似类型 <code>~string</code> 的要求，怎么就不行了&hellip;</p>
<p>根本原因是因为他的类型是 interface，而非 string 类型。所以走到了 defalut 分支的恐慌。</p>
<h2 id="总结">总结</h2>
<p>今天给大家介绍了 Go 泛型的最新消息，在上一个提案被合并后，该提案也有一些新的动静。不过 Go 官方表态，会等熟练掌握泛型实践后，再继续推动该提案。</p>
<p>我相信，原有的 <code>switch.(type)</code> 和 <code>switch type</code> 很大概率在 Go 底层会变成同一个逻辑块处理，再逐渐过渡。</p>
<p>这个提案的目的还是<strong>为了解决若干引入泛型后，所带入的 BUG/需求</strong>，正正是需要新的语法结构来解决的。</p>
<p><strong>你对此有什么看法呢</strong>，欢迎在评论区留言和交流：）</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/class-extends/">Go 为什么不支持类和继承？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/any/">Go 新关键字 any，interface 会成历史吗？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/rust-php/">Rust 内讧，PHP 主力淡出？Go：好好放假</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/118-constraints/">Go 新语法挺丑？最新的泛型类型约束介绍</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/118-build/">泛型是双刃剑？Go1.18 编译会慢近 20%</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/class-extends/"
                                                    rel="prev">Go 为什么不支持类和继承？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/again-mutex/">Go 为什么不支持可重入锁？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>